// 商品管理功能实现

DOM.on(window, 'load', () => {
  let currentPage = 1;
  const pageSize = 10;
  
  // 渲染商品表格
  function renderProducts(filters = {}) {
    const productsTable = DOM.$('#products-table tbody');
    productsTable.innerHTML = '';
    
    const productsData = dataManager.getProducts(filters, currentPage, pageSize);
    
    if (productsData.products.length === 0) {
      const emptyRow = DOM.create('tr');
      emptyRow.innerHTML = `
        <td colspan="7" style="text-align: center; padding: 40px; color: #999;">
          暂无商品数据
        </td>
      `;
      productsTable.appendChild(emptyRow);
      return;
    }
    
    productsData.products.forEach(product => {
      const row = DOM.create('tr');
      
      // 计算最低价格和总库存
      const minPrice = Math.min(...product.variants.map(v => v.price));
      const totalStock = product.variants.reduce((sum, v) => sum + v.stock, 0);
      
      // 状态徽章样式
      const statusBadge = product.status === '上架' ? 
        '<span class="badge badge-success">上架</span>' : 
        '<span class="badge badge-secondary">下架</span>';
      
      row.innerHTML = `
        <td>${product.id}</td>
        <td>${product.name}</td>
        <td>${product.categories.join(', ')}</td>
        <td>¥${minPrice.toFixed(2)}</td>
        <td>${totalStock}</td>
        <td>${statusBadge}</td>
        <td>
          <button class="btn btn-secondary" style="padding: 4px 12px; font-size: 12px; margin-right: 5px;" data-product-id="${product.id}" data-action="edit">
            编辑
          </button>
          <button class="btn btn-secondary" style="padding: 4px 12px; font-size: 12px; margin-right: 5px;" data-product-id="${product.id}" data-action="view">
            查看
          </button>
          <button class="btn btn-danger" style="padding: 4px 12px; font-size: 12px;" data-product-id="${product.id}" data-action="delete">
            删除
          </button>
        </td>
      `;
      
      productsTable.appendChild(row);
    });
    
    // 绑定操作按钮事件
    bindProductActions();
    
    // 渲染分页
    renderPagination(productsData.totalPages, currentPage);
  }
  
  // 绑定商品操作按钮事件
  function bindProductActions() {
    DOM.$$('#products-table [data-action]').forEach(btn => {
      DOM.on(btn, 'click', () => {
        const productId = btn.getAttribute('data-product-id');
        const action = btn.getAttribute('data-action');
        
        switch (action) {
          case 'edit':
            editProduct(productId);
            break;
          case 'view':
            viewProduct(productId);
            break;
          case 'delete':
            deleteProduct(productId);
            break;
        }
      });
    });
  }
  
  // 编辑商品
  function editProduct(productId) {
    const product = dataManager.data.products.find(p => p.id === productId);
    if (product) {
      // 填充表单数据（简化版）
      alert(`编辑商品: ${product.name}`);
      // 这里可以打开编辑模态框并填充数据
    }
  }
  
  // 查看商品
  function viewProduct(productId) {
    const product = dataManager.data.products.find(p => p.id === productId);
    if (product) {
      let details = `商品详情：\n`;
      details += `ID: ${product.id}\n`;
      details += `名称: ${product.name}\n`;
      details += `分类: ${product.categories.join(', ')}\n`;
      details += `状态: ${product.status}\n\n`;
      details += `SKU详情：\n`;
      
      product.variants.forEach((variant, index) => {
        const attrs = Object.entries(variant.attributes)
          .map(([key, value]) => `${key}: ${value}`)
          .join(', ');
        details += `${index + 1}. SKU: ${variant.sku} | ${attrs} | 价格: ¥${variant.price} | 库存: ${variant.stock}\n`;
      });
      
      alert(details);
    }
  }
  
  // 删除商品
  function deleteProduct(productId) {
    if (confirm('确定要删除该商品吗？')) {
      const index = dataManager.data.products.findIndex(p => p.id === productId);
      if (index !== -1) {
        dataManager.data.products.splice(index, 1);
        dataManager.saveToStorage();
        renderProducts();
      }
    }
  }
  
  // 渲染分页控件
  function renderPagination(totalPages, current) {
    // 移除旧的分页控件
    const oldPagination = DOM.$('#products-table + .pagination');
    if (oldPagination) {
      oldPagination.remove();
    }
    
    // 创建新的分页控件
    const tableContainer = DOM.$('#products-table').parentElement;
    const pagination = DOM.create('div', 'pagination');
    
    // 上一页
    const prevBtn = DOM.create('button');
    prevBtn.innerHTML = '‹';
    prevBtn.disabled = current === 1;
    DOM.on(prevBtn, 'click', () => {
      if (current > 1) {
        currentPage--;
        renderProducts();
      }
    });
    pagination.appendChild(prevBtn);
    
    // 页码按钮
    for (let i = 1; i <= totalPages; i++) {
      const pageBtn = DOM.create('button');
      pageBtn.textContent = i;
      if (i === current) {
        pageBtn.classList.add('active');
      }
      DOM.on(pageBtn, 'click', () => {
        currentPage = i;
        renderProducts();
      });
      pagination.appendChild(pageBtn);
    }
    
    // 下一页
    const nextBtn = DOM.create('button');
    nextBtn.innerHTML = '›';
    nextBtn.disabled = current === totalPages;
    DOM.on(nextBtn, 'click', () => {
      if (current < totalPages) {
        currentPage++;
        renderProducts();
      }
    });
    pagination.appendChild(nextBtn);
    
    tableContainer.appendChild(pagination);
  }
  
  // 初始化商品管理页面
  function initProducts() {
    // 绑定搜索按钮事件
    const searchBtn = DOM.$('.table-actions .btn-secondary');
    if (searchBtn) {
      DOM.on(searchBtn, 'click', () => {
        const filters = {
          name: DOM.$('input[placeholder="搜索商品名称"]').value,
          category: DOM.$('select').value || undefined,
          status: DOM.$('select:last-of-type').value || undefined
        };
        currentPage = 1;
        renderProducts(filters);
      });
    }
    
    // 绑定添加商品按钮事件
    DOM.on('#add-product-btn', 'click', () => {
      const modal = DOM.$('#add-product-modal');
      if (modal) {
        modal.classList.add('active');
      }
    });
    
    // 绑定模态框关闭事件
    DOM.on('#close-modal-btn', 'click', () => {
      const modal = DOM.$('#add-product-modal');
      if (modal) {
        modal.classList.remove('active');
      }
    });
    
    DOM.on('#cancel-add-product-btn', 'click', () => {
      const modal = DOM.$('#add-product-modal');
      if (modal) {
        modal.classList.remove('active');
      }
    });
    
    // 绑定确认添加商品事件
    DOM.on('#confirm-add-product-btn', 'click', () => {
      const form = DOM.$('#add-product-form');
      const inputs = form.querySelectorAll('input, select, textarea');
      
      // 简单验证
      let isValid = true;
      inputs.forEach(input => {
        if (input.hasAttribute('required') && !input.value) {
          isValid = false;
          input.style.borderColor = '#e74c3c';
        } else {
          input.style.borderColor = '#e0e0e0';
        }
      });
      
      if (!isValid) {
        alert('请填写所有必填字段');
        return;
      }
      
      // 创建新商品
      const newProduct = {
        name: inputs[0].value,
        variants: [{
          sku: `SKU-${Date.now()}`,
          attributes: { color: '默认', size: '均码' },
          price: parseFloat(inputs[2].value),
          stock: parseInt(inputs[3].value)
        }],
        categories: [inputs[1].options[inputs[1].selectedIndex].text],
        status: inputs[5].value === '1' ? '上架' : '下架'
      };
      
      dataManager.addProduct(newProduct);
      
      // 关闭模态框并重置表单
      const modal = DOM.$('#add-product-modal');
      modal.classList.remove('active');
      form.reset();
      
      // 重新渲染商品列表
      renderProducts();
    });
    
    // 监听视图切换事件
    DOM.on(document, 'viewChanged', (e) => {
      if (e.detail.viewId === 'products') {
        currentPage = 1;
        renderProducts();
      }
    });
  }
  
  // 初始化
  initProducts();
});